How to handle "error file not found" errors in Python?

Member

by elnora , in category: Python , a year ago

I recently started learning Python, and I am trying to read a file and I am getting: FileNotFoundError: [Errno 2] No such file or directory: 'public/test.txt' error in console. How can I handle this type of error in Python? How do I understand that before I read a file, I must first ensure that it exists? Is it possible to skip this code if the file does not exist? How do you usually handle this case?


small part of my code:

1
2
3
4
import os

with open('public/test.txt', 'r') as txt:
    print(txt.read())


Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by cyril , a year ago

@elnora To handle these types of errors, I usually use Python's try/except statement, as shown in the following code: 


1
2
3
4
5
6
7
8
9
try:
    txt = open('public/test.txt', 'r')
    print(txt.read())
except:
    # If you need to skip without logging, use pass.
    # pass
    print("Error: File not found")

print("Continue executing your code.")


by jordane.crist , 5 months ago

@elnora 

Using a try/except statement is a common approach to handle file-related errors in Python. Here's a revised version of your code with error handling:

1
2
3
4
5
6
7
8
9
import os

try:
    with open('public/test.txt', 'r') as txt:
        print(txt.read())
except FileNotFoundError:
    print("Error: File not found")

print("Continue executing your code.")


In this code, the try block includes the code that may raise an error. If a FileNotFoundError occurs, Python will jump to the except block and execute the code inside it. In this case, it will print the "Error: File not found" message. After executing the except block, code execution will continue from the next line outside the try/except statement.


If you want to skip the code without logging any message, you can use the pass statement instead of printing an error message. Uncomment pass (remove the # in front of it) and comment out the print("Error: File not found") line to use this option.


Remember to adjust the file path and name to match the actual path and name of the file you want to read.